package com.delio.client.produccion.clientes;

import java.util.ArrayList;
import java.util.List;

import com.delio.client.idioma.DelioConstants;
import com.delio.client.produccion.direccionclientes.DireccionCliente;
import com.delio.client.produccion.direccionclientes.DireccionClientes;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.binding.FieldBinding;
import com.extjs.gxt.ui.client.binding.FormBinding;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.BeanModelFactory;
import com.extjs.gxt.ui.client.data.BeanModelLookup;
//import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.GridEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.button.ButtonBar;
//import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.extjs.gxt.ui.client.widget.form.Field;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.HiddenField;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.form.TextArea;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.form.Validator;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.EditorGrid;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.filters.GridFilters;
import com.extjs.gxt.ui.client.widget.grid.filters.StringFilter;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.extjs.gxt.ui.client.widget.toolbar.PagingToolBar;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.core.client.GWT;

public class ClienteForm extends ContentPanel{
	private DelioConstants x = GWT.create(DelioConstants.class);
	public Button btnNuevoDireccionCliente,btnDeleteDireccionCliente,btnGuardarDireccionCliente,btnGuardar,btnDeleteCliente;
	ToolBar toolBar,toolBar1 ;
	ContentPanel cpw,ctp,cpi,cpg;
	BorderLayoutData sup,inf,east,center,nor,c,cen,cg;
	TextField<String> codigo,razonsocial,nombres,nombrecomercial,telefono,celular,email,rpc,rpm,txtDireccion;
	TextArea observacion;
	HiddenField<String> id=null;
	NumberField ruc;
	private FormBinding formbinding;
	FormPanel fp;
	private BeanModel selectedModel,selectedModel1;
	EditorGrid<BeanModel> grid1;
   // ComboBox<ModelData> cmbDC;
    

 	public ClienteForm(){
		setHeaderVisible(false);
		BorderLayout layout = new BorderLayout();
		setLayout(layout);
		formulario();
	    Clientes.getPaginate();
        DireccionClientes.listardireccioncliente();
        DireccionClientes.listardireccionclienteCombo();
        cpw = new ContentPanel();
	    cpw.setHeading("Editar Cliente");
	    cpw.setIconStyle("images/icons/people.png");
	    cpw.setLayout(new FitLayout());
	    
	    cpw.add(fp);
	     
	    east = new BorderLayoutData(LayoutRegion.EAST,350);
	    east.setMargins(new Margins(2));
	    east.setSplit(true);
	    east.setCollapsible(true);
	    
	    
	    center  = new BorderLayoutData(LayoutRegion.CENTER);
	    center.setMargins(new Margins(2));
	    center.setCollapsible(true);
	    
	    ctp = new ContentPanel();
	    ctp.setHeaderVisible(false);
	    ctp.setLayout(new BorderLayout());
		 	    
		nor  = new BorderLayoutData(LayoutRegion.NORTH,350);
		nor.setMargins(new Margins(3));
		 
		cpi = new ContentPanel();
		cpi.setHeading("Listado de Clientes");
		cpi.setIconStyle("images/icons/table.png");
		cpi.setLayout(new BorderLayout());
		  
		c = new BorderLayoutData(LayoutRegion.CENTER);
		 		    
		cen   = new BorderLayoutData(LayoutRegion.CENTER);
		cen.setMargins(new Margins(3));
		    
		cpg = new ContentPanel();
		//cpg.setHeading("Listado de Direcciones Cliente");
		//cpg.setIconStyle("images/icons/table.png");
		cpg.setHeaderVisible(false);
		cpg.setLayout(new BorderLayout());
			
	 	cg = new BorderLayoutData(LayoutRegion.CENTER,100);
		    
	    final PagingToolBar toolBarPag = new PagingToolBar(10);
        toolBarPag.bind(Clientes.loader);
        
        List<ColumnConfig> conf = new ArrayList<ColumnConfig>();
        CheckBoxSelectionModel<BeanModel> sm = new CheckBoxSelectionModel<BeanModel>();
    
        conf.add(sm.getColumn()); 
        ColumnConfig col  = new ColumnConfig("codigo",x.nrocliente(),100);
	    conf.add(col);
	    col  = new ColumnConfig("razonsocial",x.razonSocial(),100);
	    conf.add(col);
	    col  = new ColumnConfig("nombres",x.Nombres(),100);
	    conf.add(col);
	    col  = new ColumnConfig("nombrecomercial",x.nombreComercial(),100);
	    conf.add(col);
	    col  = new ColumnConfig("ruc",x.ruc(),100);
	    conf.add(col);
	    col  = new ColumnConfig("telefono",x.telefono(),100);
	    conf.add(col);
	    col  = new ColumnConfig("celular",x.celular(),100);
	    conf.add(col);
	    col  = new ColumnConfig("email",x.email(),100);
	    conf.add(col);
	    col  = new ColumnConfig("rpc",x.rpc(),100);
	    conf.add(col);
	    col  = new ColumnConfig("rpm",x.rpm(),100);
	    conf.add(col);
	    col  = new ColumnConfig("observacion",x.clienteobservacion(),200);
	    conf.add(col);
	    
	    final ColumnModel cm = new ColumnModel(conf);
	    
	    Grid<BeanModel> grid = new Grid<BeanModel>(Clientes.store, cm);  
        grid.addListener(Events.Attach, new Listener<GridEvent<BeanModel>>() {  
          public void handleEvent(GridEvent<BeanModel> be) {  
        	  Clientes.loader.load(0, 10);  
          }  
        }); 
        sm.setSelectionMode(SelectionMode.SINGLE);
        grid.setSelectionModel(sm);
        grid.getSelectionModel().addListener(Events.SelectionChange,
           new Listener<SelectionChangedEvent<BeanModel>>() {
			@Override
			public void handleEvent(SelectionChangedEvent<BeanModel> be) {		
    		   if(be.getSelection().size() == 1) {
	             formbinding.bind((BeanModel) be.getSelection().get(0));
	             selectedModel = be.getSelectedItem();
	             DireccionClientes.cliente_id = selectedModel.get("id");
	             DireccionClientes.loaderDireccionCliente.load();
	             btnNuevoDireccionCliente.setEnabled(true);
  	           }
    			if(be.getSelection().size()==0){
    			 DireccionClientes.storeDireccionCliente.removeAll();
                 clearForm();
                 btnNuevoDireccionCliente.setEnabled(false);
                 btnGuardarDireccionCliente.setEnabled(false);
                 formbinding.unbind();
               }
    			if(be.getSelection().size()>1)
    			  formbinding.unbind();
			}
          });
        
        grid.setLoadMask(true);  
        grid.setBorders(true);       
        
        GridFilters filters = new GridFilters();
        StringFilter codigoFilter = new StringFilter("codigo");        
        StringFilter razonsocialFilter = new StringFilter("razonsocial");
        StringFilter nombresFilter = new StringFilter("nombres");
        StringFilter nombrecomercialFilter = new StringFilter("nombrecomercial");
        StringFilter rucFilter = new StringFilter("ruc");
        StringFilter telefonoFilter = new StringFilter("telefono");
        StringFilter celularFilter = new StringFilter("celular");
        StringFilter emailFilter = new StringFilter("email");
        StringFilter rpcFilter = new StringFilter("rpc");
        StringFilter rpmFilter = new StringFilter("rpm");
        StringFilter observacionFilter = new StringFilter("observacion");
          
        filters.addFilter(codigoFilter);        
        filters.addFilter(razonsocialFilter);        
        filters.addFilter(nombresFilter);        
        filters.addFilter(nombrecomercialFilter);
        filters.addFilter(rucFilter);
        filters.addFilter(telefonoFilter);
        filters.addFilter(celularFilter);
        filters.addFilter(emailFilter);
        filters.addFilter(rpcFilter);
        filters.addFilter(rpmFilter);
        filters.addFilter(observacionFilter);
         
        grid.addPlugin(filters);                
        grid.addPlugin(sm);
        formbinding = new FormBinding(fp);
        formbinding.setStore(Clientes.store);
	    formbinding.addFieldBinding(new FieldBinding(id,"id"));
	    formbinding.addFieldBinding(new FieldBinding(codigo,"codigo"));
	    formbinding.addFieldBinding(new FieldBinding(razonsocial,"razonsocial"));
	    formbinding.addFieldBinding(new FieldBinding(nombres,"nombres"));
	    formbinding.addFieldBinding(new FieldBinding(nombrecomercial,"nombrecomercial"));
	    formbinding.addFieldBinding(new FieldBinding(ruc,"ruc"));
	    formbinding.addFieldBinding(new FieldBinding(telefono,"telefono"));
	    formbinding.addFieldBinding(new FieldBinding(celular,"celular"));
	    formbinding.addFieldBinding(new FieldBinding(email,"email"));
	    formbinding.addFieldBinding(new FieldBinding(rpc,"rpc"));
	    formbinding.addFieldBinding(new FieldBinding(rpm,"rpm"));
	    formbinding.addFieldBinding(new FieldBinding(observacion,"observacion"));
	    
	    List<ColumnConfig> conf1 = new ArrayList<ColumnConfig>();
	    CheckBoxSelectionModel<BeanModel> sm1 = new CheckBoxSelectionModel<BeanModel>();
	    
        conf1.add(sm1.getColumn()); 
        ColumnConfig col1 = new ColumnConfig("direccion",x.direccioncliente(),500);
        txtDireccion = new TextField<String>();  
        txtDireccion.setAllowBlank(false);  
        col1.setEditor(new CellEditor(txtDireccion));  
        conf1.add(col1);  	
          
        final ColumnModel cm1 = new ColumnModel(conf1);
        grid1 = new EditorGrid<BeanModel>(DireccionClientes.storeDireccionCliente, cm1);
		grid1.setBorders(true);
        grid1.setLoadMask(true); 
        grid1.setBorders(true);   
        grid1.addPlugin(sm1);

        grid1.setSelectionModel(sm1);
        grid1.getSelectionModel().addListener(Events.SelectionChange,
           new Listener<SelectionChangedEvent<BeanModel>>() {
			@Override
			public void handleEvent(SelectionChangedEvent<BeanModel> be) {
			  if(be.getSelection().size()==0){
			      btnDeleteDireccionCliente.setEnabled(false);
				  btnGuardarDireccionCliente.setEnabled(false);
			  }
			  if(be.getSelection().size()==1){
				  btnDeleteDireccionCliente.setEnabled(true);
				  btnGuardarDireccionCliente.setEnabled(true);
			      selectedModel1 = be.getSelectedItem();
	              DireccionClientes.direccioncliente_id = selectedModel1.get("id");
	          }
     		}
        });	 
        toolBar = new ToolBar(); 
        btnDeleteCliente = new Button("Eliminar", IconHelper.createPath("images/icons/delete.gif"));
        btnDeleteCliente.setEnabled(false);
        toolBar.add(btnDeleteCliente);
        btnDeleteCliente.addSelectionListener(new SelectionListener<ButtonEvent>(){
    	   public void componentSelected(ButtonEvent ce){
			  if(id.getValue() != null){	 
			    Listener<MessageBoxEvent> callback = new Listener<MessageBoxEvent>() {	 
				  public void handleEvent(MessageBoxEvent be) {
		           if (be.getButtonClicked().getItemId().equals(Dialog.YES)) { 
				        Clientes.eliminar(Integer.parseInt(id.getValue()));
					    Clientes.loader.load();
			         }
		            }
			      };
			       String msg = "Esta seguro que desea eliminar al Cliente?";
			       MessageBox.confirm(x.eliminarCliente(), msg, callback);
			 	  }else{
				   MessageBox.alert(x.seleccionar(), "Seleccione una fila porfavor", null);
			      }
			 }
		  });
             
        cpi.add(grid,c);
		cpi.setBottomComponent(toolBarPag);		
		toolBar1 = new ToolBar();
		btnNuevoDireccionCliente = new Button("Nuevo",IconHelper.createPath("images/icons/new.gif"));
		btnNuevoDireccionCliente.setEnabled(false);
		toolBar1.add(btnNuevoDireccionCliente);
		btnNuevoDireccionCliente.addSelectionListener(new SelectionListener<ButtonEvent>(){
		  public void componentSelected(ButtonEvent ce){
			btnGuardarDireccionCliente.setEnabled(true);
			DireccionCliente dc = new DireccionCliente();
			dc.setDireccion("");
			BeanModelFactory beanModelFactory =  BeanModelLookup.get().getFactory(dc.getClass());
			grid1.stopEditing();
		
			DireccionClientes.storeDireccionCliente.insert(beanModelFactory.createModel(dc), 0);
			grid1.startEditing(DireccionClientes.storeDireccionCliente.indexOf(beanModelFactory.createModel(dc)), 0);
		   }
		});
		btnGuardarDireccionCliente = new Button("Guardar",IconHelper.createPath("images/icons/new.gif"));
		btnGuardarDireccionCliente.setEnabled(false);
		toolBar1.add(btnGuardarDireccionCliente);
		btnGuardarDireccionCliente.addSelectionListener(new SelectionListener<ButtonEvent>(){
		public void componentSelected(ButtonEvent ce){
		   DireccionCliente dc = new DireccionCliente();
		   dc.setCliente_id(DireccionClientes.cliente_id);			    
		   dc.setDireccion(txtDireccion.getValue());
		   btnGuardarDireccionCliente.setEnabled(false);	  
		  if(DireccionClientes.direccioncliente_id==null){
		   DireccionClientes.guardar(dc);
		   }
		  if(DireccionClientes.direccioncliente_id!=null){
		   dc.setId(DireccionClientes.direccioncliente_id);
		   DireccionClientes.actualizar(dc);
		   }
		   DireccionClientes.storeDireccionCliente.commitChanges();
		}
    	});
		
		btnDeleteDireccionCliente = new Button("Eliminar",IconHelper.createPath("images/icons/delete.gif"));
		btnDeleteDireccionCliente.setEnabled(false);
		toolBar1.add(btnDeleteDireccionCliente);
		btnDeleteDireccionCliente.addSelectionListener(new SelectionListener<ButtonEvent>(){
		  public void componentSelected(ButtonEvent ce){
			    Listener<MessageBoxEvent> callback = new Listener<MessageBoxEvent>() {	 
				  public void handleEvent(MessageBoxEvent be) {
		           if (be.getButtonClicked().getItemId().equals(Dialog.YES)) { 
				        DireccionClientes.eliminar(DireccionClientes.direccioncliente_id);
					    DireccionClientes.loaderDireccionCliente.load();
			         }
		           }
			     };
			     String msg = "Esta seguro que desea eliminar esta direccion del Cliente?";
			     MessageBox.confirm("Eliminar Direccion Cliente?", msg, callback);
	 		 }
		   });
	    
		cpg.setTopComponent(toolBar1);
		cpg.add(grid1,cg);
	
		ctp.setTopComponent(toolBar);
		ctp.add(cpi,nor);
		ctp.add(cpg,cen);
		
        add(ctp,center);
	    add(cpw,east);
	    
	}
 
	public ButtonBar bbutonbar(){
		  ButtonBar bb = new ButtonBar();
		  btnGuardar = new Button("Guardar",IconHelper.createPath("images/icons/save_all.png"));		  
		  btnGuardar.addSelectionListener(new SelectionListener<ButtonEvent>(){
			public void componentSelected(ButtonEvent ve){
			   if(validate()){  
				final Cliente c = new Cliente();
				 c.setCodigo(codigo.getValue());
				 c.setRazonsocial(razonsocial.getValue());
				 c.setNombres(nombres.getValue());
				 c.setNombrecomercial(nombrecomercial.getValue());
				 c.setRuc(ruc.getValue().longValue());
				 c.setTelefono(telefono.getValue());
				 c.setCelular(celular.getValue());
				 c.setEmail(email.getValue());
				 c.setRpc(rpc.getValue());
				 c.setRpm(rpm.getValue());
				 c.setObservacion(observacion.getValue());
					 
				 if(id.getValue() == null){	
			       Clientes.guardar(c);
			       Clientes.loader.load();
			       clearForm();
			     }
			     if(id.getValue() != null){
				 Listener<MessageBoxEvent> callback = new Listener<MessageBoxEvent>() {	 
				  public void handleEvent(MessageBoxEvent be) {
				    if(be.getButtonClicked().getItemId().equals(Dialog.YES)) {  
				     c.setId(Integer.parseInt(id.getValue()));
				     Clientes.actualizar(c);
					 Clientes.loader.load();
					}
					}
			      };
			      String msg = "Esta seguro que desea Actualizar el Cliente?";
			      MessageBox.confirm("Actualizar Cliente?", msg, callback);
			 	  }
		        }
			  }
	       });
	
		  HorizontalAlignment align =  HorizontalAlignment.CENTER;
		  bb.add(btnGuardar);
		  bb.setAlignment(align);
		  return bb;
	  }
	 
	public boolean validate(){
       return fp.isValid();
	}
	 
			  
	public void formulario(){
		fp = new FormPanel();
		fp.setHeaderVisible(false);
		fp.setFrame(true);
		id = new HiddenField<String>();
		id.setVisible(false);
		codigo = new TextField<String>();
		codigo.setFieldLabel(x.nrocliente());
		codigo.setAllowBlank(true);
		codigo.setEnabled(false);
		razonsocial = new TextField<String>();
		razonsocial.setFieldLabel(x.razonSocial());
		razonsocial.setAllowBlank(true);
		razonsocial.getSelectOnFocus();
		nombres = new TextField<String>();
		nombres.setFieldLabel(x.representante());
		nombrecomercial = new TextField<String>();
		nombrecomercial.setFieldLabel(x.nombreComercial());
		ruc = new NumberField();
		ruc.setPropertyEditorType(Long.class);
		ruc.setFieldLabel(x.ruc());
		ruc.setMaxLength(11);
		ruc.setMinLength(11);
		ruc.setAllowBlank(true);
		telefono = new TextField<String>();
		telefono.setFieldLabel(x.telefono());
		celular = new TextField<String>();
		celular.setFieldLabel(x.celular());
		email = new TextField<String>();
		email.setFieldLabel(x.email());
		final String emailReg = "[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}";
	    final String errMsg = "Not a valid email address!";
	    email.setValidator(new Validator() {
	      public String validate(Field<?> field, String value) {
	        if (!value.toUpperCase().matches(emailReg))
	          return errMsg;
	        return null;
	      }
	    });
		rpc = new TextField<String>();
		rpc.setFieldLabel(x.rpc());
		rpm = new TextField<String>();
		rpm.setFieldLabel(x.rpm());
		observacion = new TextArea();
		observacion.setFieldLabel(x.clienteobservacion()); 
	    fp.add(id);	
		fp.add(codigo,new FormData("-20"));
		fp.add(razonsocial,new FormData("-20"));
		fp.add(nombres,new FormData("-20"));
		fp.add(nombrecomercial,new FormData("-20"));
		fp.add(ruc,new FormData("-20"));
        fp.add(telefono,new FormData("-20"));
        fp.add(celular,new FormData("-20"));
        fp.add(email,new FormData("-20"));
        fp.add(rpc,new FormData("-20"));
        fp.add(rpm,new FormData("-20"));
        fp.add(observacion,new FormData("-20"));
        fp.add(bbutonbar());
	}
	
   public void clearForm(){
	   fp.clear();
    }
}